'use client'

import React, { useState } from 'react';
import { RadioGroup } from '@headlessui/react';
import { ComputerDesktopIcon, MoonIcon, SunIcon } from '@heroicons/react/24/outline';
import DialogWrapper from './dialog-wrapper';
import { UserSettings } from '@/types/user';
import ThemeSelector from './theme-selector';
import { useTheme } from '@/hooks/use-theme';

interface AppearanceDialogProps {
  isOpen: boolean;
  onClose: () => void;
  settings: UserSettings | null;
  onSave: (settings: UserSettings) => Promise<void>;
}

export default function AppearanceDialog({
  isOpen,
  onClose,
  settings,
  onSave
}: AppearanceDialogProps) {
  const { themeColor, setThemeColor } = useTheme();
  const [editedSettings, setEditedSettings] = useState<UserSettings | null>(settings);
  const [isSaving, setIsSaving] = useState(false);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  
  // 当settings变化时更新编辑状态
  React.useEffect(() => {
    setEditedSettings(settings);
    setSuccessMessage(null);
    setErrorMessage(null);
  }, [settings]);

  if (!editedSettings) return null;

  // 主题选项
  const themeOptions = [
    { id: 'light', name: '明亮模式', icon: SunIcon },
    { id: 'dark', name: '暗黑模式', icon: MoonIcon },
    { id: 'system', name: '跟随系统', icon: ComputerDesktopIcon },
  ];

  // 语言选项
  const languageOptions = [
    { id: 'zh_CN', name: '简体中文' },
    { id: 'en_US', name: 'English' },
  ];

  // 保存设置
  const handleSave = async () => {
    if (!editedSettings) return;
    
    setIsSaving(true);
    setSuccessMessage(null);
    setErrorMessage(null);
    
    try {
      // 保存主题色和语言设置
      await onSave({
        ...editedSettings,
        // 确保主题色和语言都被正确保存
        themeColor: themeColor
      });
      
      // 如果是语言切换，刷新页面应用新语言
      const oldLanguage = settings?.language;
      if (oldLanguage !== editedSettings.language) {
        setSuccessMessage('语言设置已更新，页面将刷新...');
        setTimeout(() => {
          window.location.reload();
        }, 1500);
        return; // 语言更改后不需要关闭对话框，因为页面会刷新
      } else {
        setSuccessMessage('外观设置已更新');
        
        // 成功后关闭对话框
        setTimeout(() => {
          onClose();
        }, 1500);
      }
    } catch (error) {
      console.error('更新外观设置失败:', error);
      setErrorMessage('更新失败，请稍后重试');
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <DialogWrapper
      isOpen={isOpen}
      onClose={onClose}
      title="外观与语言"
      size="md"
    >
      {successMessage && (
        <div className="mb-4 p-3 bg-green-50 border-l-4 border-green-500 text-green-700 rounded-md">
          <p>{successMessage}</p>
        </div>
      )}
      
      {errorMessage && (
        <div className="mb-4 p-3 bg-red-50 border-l-4 border-red-500 text-red-700 rounded-md">
          <p>{errorMessage}</p>
        </div>
      )}
      
      <div className="space-y-6">
        {/* 主题模式 */}
        <div>
          <h3 className="text-lg font-medium text-gray-900">主题模式</h3>
          <p className="text-sm text-gray-500 mb-4">选择您偏好的界面模式</p>
          
          <RadioGroup 
            value={editedSettings.theme} 
            onChange={(value) => setEditedSettings(prev => prev ? {...prev, theme: value as 'light' | 'dark' | 'system'} : null)}
            className="mt-2"
          >
            <div className="grid grid-cols-3 gap-3">
              {themeOptions.map((option) => (
                <RadioGroup.Option
                  key={option.id}
                  value={option.id}
                  className={({ active, checked }) =>
                    `${
                      checked ? 'bg-[var(--primary-color)] text-white' : 'bg-white text-gray-900'
                    }
                    ${
                      active ? 'ring-2 ring-offset-2 ring-[var(--primary-color)]' : ''
                    }
                    relative flex cursor-pointer rounded-lg px-5 py-4 shadow-md focus:outline-none`
                  }
                >
                  {({ active, checked }) => (
                    <>
                      <div className="flex w-full items-center justify-center">
                        <div className="flex items-center">
                          <div className="text-sm">
                            <RadioGroup.Label
                              as="p"
                              className={`font-medium ${
                                checked ? 'text-white' : 'text-gray-900'
                              }`}
                            >
                              <option.icon className="h-6 w-6 mx-auto mb-2" />
                              {option.name}
                            </RadioGroup.Label>
                          </div>
                        </div>
                      </div>
                    </>
                  )}
                </RadioGroup.Option>
              ))}
            </div>
          </RadioGroup>
        </div>
        
        {/* 主题颜色 */}
        <div>
          <h3 className="text-lg font-medium text-gray-900">主题颜色</h3>
          <p className="text-sm text-gray-500 mb-4">选择您喜欢的主题颜色</p>
          
          <ThemeSelector
            selectedColor={themeColor}
            onChange={setThemeColor}
          />
        </div>
        
        {/* 语言设置 */}
        <div>
          <h3 className="text-lg font-medium text-gray-900">语言</h3>
          <p className="text-sm text-gray-500 mb-4">选择您偏好的界面语言</p>
          
          <RadioGroup 
            value={editedSettings.language} 
            onChange={(value) => setEditedSettings(prev => prev ? {...prev, language: value as 'zh_CN' | 'en_US'} : null)}
            className="mt-2"
          >
            <div className="grid grid-cols-2 gap-3">
              {languageOptions.map((option) => (
                <RadioGroup.Option
                  key={option.id}
                  value={option.id}
                  className={({ active, checked }) =>
                    `${
                      checked ? 'bg-[var(--primary-color)] text-white' : 'bg-white text-gray-900'
                    }
                    ${
                      active ? 'ring-2 ring-offset-2 ring-[var(--primary-color)]' : ''
                    }
                    relative flex cursor-pointer rounded-lg px-5 py-4 shadow-md focus:outline-none`
                  }
                >
                  {({ active, checked }) => (
                    <>
                      <div className="flex w-full items-center justify-center">
                        <div className="flex items-center">
                          <div className="text-sm">
                            <RadioGroup.Label
                              as="p"
                              className={`font-medium ${
                                checked ? 'text-white' : 'text-gray-900'
                              }`}
                            >
                              {option.name}
                            </RadioGroup.Label>
                          </div>
                        </div>
                      </div>
                    </>
                  )}
                </RadioGroup.Option>
              ))}
            </div>
          </RadioGroup>
        </div>
      </div>
      
      {/* 操作按钮 */}
      <div className="mt-6 flex justify-end space-x-3">
        <button
          type="button"
          className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
          onClick={onClose}
          disabled={isSaving}
        >
          取消
        </button>
        <button
          type="button"
          className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-[var(--primary-color)] hover:bg-[var(--primary-hover)] focus:outline-none disabled:opacity-50"
          onClick={handleSave}
          disabled={isSaving}
        >
          {isSaving ? '保存中...' : '保存'}
        </button>
      </div>
    </DialogWrapper>
  );
} 